import getopt


class Arg(object):
    def __init__(self, short_arg, long_arg, value=None, description=''):
        self.value = value
        self.short_arg = short_arg
        self.long_arg = long_arg
        self.description = description

    def dump(self):
        return '-{:3}--{:20}{:15}{:}'.format(self.short_arg,
                                                  self.long_arg,
                                                  str(self.value) if self.value else 'None',
                                                  self.description)


class SimpleConfig(object):
    IP = '127.0.0.1'
    PORT = 2049
    INTERVAL = -1
    ROLLING = 1

    def __init__(self):
        self.server = Arg('s', 'server', description='work as server or client')
        self.ip = Arg('i', 'ip', SimpleConfig.IP, description='config server ip address')
        self.port = Arg('p', 'port', SimpleConfig.PORT, description='config server port')
        self.verbose = Arg('v', 'verbose', description='verbose details')
        self.help = Arg('h', 'help', description='show help informations')
        self.server_interval = Arg('n', 'server_interval', SimpleConfig.INTERVAL,
                                   description='set web refresh interval in milliseconds')
        self.rolling_mean = Arg('m', 'rolling_mean', SimpleConfig.ROLLING,
                                description='format output data using rolling mean value')

    def get_long_opts(self):
        return [v.long_arg + ('=' if v.value else '') for k, v in vars(self).items()]

    def get_short_opts(self):
        return ''.join(['-' + v.short_arg + (':' if v.value else '') for k, v in vars(self).items()])

    def update_config(self, k, v):
        k = k.split('-')[-1]
        for kk, vv in vars(self).items():
            if k in (vv.short_arg, vv.long_arg):
                vv.value = v if v else True

    def print_config(self):
        for k, v in vars(self).items():
            print(v.dump())

    @classmethod
    def parse_opt(cls, argv):
        config = SimpleConfig()
        opts, args = getopt.getopt(argv, config.get_short_opts(), longopts=config.get_long_opts())
        print(opts)
        for k, v in opts:
            config.update_config(k, v)
        config.check_opt()
        return config

    def print_help(self):
        for kk, vv in vars(self).items():
            print(vv.dump())

    def check_opt(self):
        self.print_config()
        if self.help.value:
            exit(0)
